/*
 * declare_optimus.c
 *
 *  Created on: 2013-5-4
 *      Author: xkaying
 */

#include "declare_optimus.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#include "../common/token.h"
#include "../common/list.h"
#include "../common/stack.h"
#include "declare_expression.h"

typedef struct _declarenode
{
	int no; //节点编号,节点编号表示节点的数据名称,0表示无用节点.
	char *name; //节点名字,如果为0,则表示使用系统名
	int table[256];
} DeclareNode;

struct _declareoptimus
{
	int table[256];
	////////////////
	//节点列表
	List *pnodeList;

	List *pdatalist;
	List *ptokenlist;
	List *pvarlist;
};

DeclareNode *DeclareNodeInit()
{
	DeclareNode *pnode;
	pnode = (DeclareNode*) calloc(1, sizeof(DeclareNode));
	return pnode;
}

int DeclareExpressionParser(int *buff, Stack *pstack)
{
	assert(buff);
	assert(pstack);
	//操作符號堆棧
	Stack *opstack;
	opstack = StackInit();
	Token *ptoken;
	Token *psrc;
	Token *pdest;
	psrc = 0;
	pdest = 0;
	ptoken = (Token*) StackPop(pstack);
	//进行token对倒
	while (ptoken) {
		StackPush(opstack, ptoken);
		ptoken = (Token*) StackPop(pstack);
	}
	ptoken = (Token*) StackPop(opstack);
	while (ptoken) {
		if (ptoken->type == TokenType_Variable
				|| ptoken->type == TokenType_Value
				|| ptoken->type == TokenType_String
				|| ptoken->type == TokenType_None) {
			StackPush(pstack,ptoken);
		}else{
			pdest=(Token*)StackPop(pstack);
			psrc=(Token*)StackPop(pstack);
			DeclareExpressionCompute(buff,psrc,pdest,ptoken->type);
		}
	}

	return 0;
}

int DeclareExpressionCompute(int *buff, Token *psrc, Token *pdest, int type)
{
	assert(buff);
	int x, y;
	switch (type)
	{
		case TokenType_DeclareOr: {
			x = TokenDeclareConvert(psrc);
			y = TokenDeclareConvert(pdest);
			buff[x] = 1;
			buff[y] = 1;
			break;
		}
		case TokenType_DeclareMore: {
			x = TokenDeclareConvert(psrc);
			for (; x < 256; x++) {
				buff[x] = 1;
			}
			break;
		}
		case TokenType_DeclareLess: {
			x = TokenDeclareConvert(psrc);
			for (; x >= 0; x--) {
				buff[x] = 1;
			}
			break;
		}
		case TokenType_DeclareBetween: {
			int x;
			int y;
			x = TokenDeclareConvert(psrc);
			y = TokenDeclareConvert(pdest);
			for (; x <= y; x++) {
				buff[x] = 1;
			}
			break;
		}
	}
	return 1;
}

DeclareOptimus *DeclareExpressionOptimus(List *plist)
{
	assert(plist);
	DeclareOptimus *pdo;
	pdo = (DeclareOptimus*) malloc(sizeof(DeclareOptimus));
	pdo->pdatalist = ListInit();
	pdo->ptokenlist = ListInit();
	pdo->pvarlist = ListInit();
	////////////////////////////////////////////////////
	DeclareNode *pnode;
	ListCursor *pcursor;
	pcursor = ListGetCursor(plist);
	///////////////////////////////
	/*
	 * 第一步 扩充所有列表,使数据节点和正常节点分开.
	 * 第二部,对所有子节点进行交集处理.i并再次分拆子节点.
	 * 第三部,合并无用节点.
	 * 可得到一个最简单的节点树 和节点表.
	 */
	///////////////////////////////////
	DeclareExpression *pde;
	pde = ListForeach(plist, pcursor);
	while (pde) {
		//
		pnode = DeclareNodeInit();
		//DeclareExpressionParser(pnode->table,pde->ptokenstack);
		//对pde进行逆波兰解析,生成declare,生成当前的数值
	}
	return pdo;
}

